#include "Ringqueue.hpp"
#include "Task.hpp"
#include"Log.hpp"
#include <pthread.h>
#include <unistd.h>
#include <ctime>

// 我们不清楚生产者和消费者谁先被调度（这是由调度器决定的），但是通过PV操作可知，一定是生产者先跑，因为如果没有
// 数据资源，消费者要被阻塞的（通过sem_wait）
void *Productor(void *args)
{
    Ringqueue<Task> *rq = static_cast<Ringqueue<Task> *>(args);
    int cnt = 100;
    while (true)
    {

        // 1.有数据
        int data1 = rand() % 10;
        usleep(1000); // 为了防止生成的数更加随机，所以休眠一会
        int data2 = rand() % 10;

        char oper = opers[rand() % (opers.size())];
        Task t(data1, data2, oper);
        // for debug
        string task_string = t.Printtask();
        cout << "productor    task;   " << task_string << endl;

        rq->Push(t);
        sleep(1); // 让生产者慢一点
    }
}

void *Consumer(void *args)
{
    Ringqueue<Task> *rq = static_cast<Ringqueue<Task> *>(args);
    while (true)
    {
        Task t;
        rq->Pop(&t);

        t.Run();
        cout << "consumer data:    " << t.Printresult() << endl;
        // sleep(1);
    }
}

void test1()
{
    srand((uint64_t)time(nullptr) ^ pthread_self());
    pthread_t c[3], p[2];

    // Ringqueue<int>* rq=new Ringqueue<int>();
    Ringqueue<Task> *rq = new Ringqueue<Task>();

    pthread_create(&p[0], nullptr, Productor, rq);
    pthread_create(&p[1], nullptr, Productor, rq);
    pthread_create(&p[2], nullptr, Productor, rq);
    pthread_create(&c[0], nullptr, Consumer, rq);
    pthread_create(&c[1], nullptr, Consumer, rq);

    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(p[2], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
}
int main()
{
    Log log;
    log.LogMessage(Debug,"hello %d %s %f",10,"bite",3.14);
    log.LogMessage(Info,"hello %d %s %f",10,"bite",3.14);
    log.LogMessage(Error,"hello %d %s %f",10,"bite",3.14);
    log.LogMessage(Fatal,"hello %d %s %f",10,"bite",3.14);
    return 0;
}